package net.lovesrc.allin.biz.idcard;

import com.zhouzhou.fastjava.BizException;
import net.lovesrc.allin.biz.BaseService;
import net.lovesrc.allin.utils.ImageUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.SystemUtils;

import java.io.File;
import java.util.Arrays;
import java.util.Optional;

public class IdCradFromFileService extends BaseService {
    public static File ROOT;

    public static File TMP_ROOT;

    static {
        if (SystemUtils.IS_OS_LINUX) {
            ROOT = new File("/soft/idcard/all/正反/身份证正反.1");
            TMP_ROOT = new File("/tmp/idcard/all/正反/身份证正反.1");
        } else {
            ROOT = new File("e:/myself/idcard/身份证正反+手持。2/");
            TMP_ROOT = new File("e:/myself/temp/idcard/身份证正反+手持。2/");
        }
    }

    /**
     *  String[] ，姓名。身份证号，正面路径，反面路径
     * @return
     */
    public static String[] getIdCard() {
        int index = 1;
        while ((ROOT.listFiles() == null || ROOT.listFiles().length == 0) && index < 5) {
            index++;
            ROOT = new File("/soft/idcard/all/正反/身份证正反." + index);
            TMP_ROOT = new File("/tmp/idcard/all/正反/身份证正反." + index);

        }
        if (!TMP_ROOT.exists()) {
            TMP_ROOT.mkdirs();
        }

        if (ROOT.listFiles() == null || ROOT.listFiles().length == 0) {
            throw BizException.messageOf("没有可有的身份证了");
        }

        File[] listFiles = ROOT.listFiles();
        for (int i = 0; i < listFiles.length; i++) {
            File file = listFiles[i];
            File[] files = file.listFiles();
            Optional<File> first = Arrays.stream(files).filter(file1 -> file1.getName().contains("信息.txt"))
                    .findFirst();
            Optional<File> jpg1 = Arrays.stream(files).filter(file1 -> file1.getName().contains("1."))
                    .findFirst();
            Optional<File> jpg2 = Arrays.stream(files).filter(file1 -> file1.getName().contains("2."))
                    .findFirst();

            String value = ImageUtils.getValue(first.get());
            String identityNo = StringUtils.substringAfter(value, "----").replaceAll("\\s", "");
            String name = StringUtils.substringBefore(value, "----").replaceAll("\\s", "");
            file.renameTo(new File(TMP_ROOT.getAbsolutePath() + "/" + file.getName()));
            return new String[]{name, identityNo, TMP_ROOT.getAbsolutePath() + "/" + file.getName() + "/" + jpg1.get().getName(), TMP_ROOT.getAbsolutePath() + "/" + file.getName() + "/" + jpg2.get().getName()};
        }

        return null;

    }

    public static void main(String[] args) {
        System.out.println(StringUtils.substringBefore("1232331\r\n", "----").replaceAll("\\s", ""));
    }

}
